// 封装一个渲染函数
let creator = '噶'
function render () {
  axios('http://hmajax.itheima.net/api/books', { params: { creator } }).then(
    res => {
      const html = res.data.data
        .map(item => {
          return `
        <tr>
          <td>${item.id}</td>
          <td>${item.bookname}</td>
          <td>${item.author}</td>
          <td>${item.publisher}</td>
          <td>
            <span class="del" data-id=${item.id}>删除</span>
            <span class="edit" data-id=${item.id}>编辑</span>
          </td>
        </tr>
        
        `
        })
        .join('')
      document.querySelector('.list').innerHTML = html
    }
  )
}
render()

// 弹窗的显示跟隐藏
const modalDom = document.querySelector('.add-modal')
const addModal = new bootstrap.Modal(modalDom)

// 点击添加
document.querySelector('.add-btn').addEventListener('click', function () {
  // 收集表单数据
  const form = serialize(document.querySelector('.add-form'), {
    hash: true,
    empty: true
  })

  axios({
    url: 'http://hmajax.itheima.net/api/books',
    method: 'POST',
    data: {
      creator,
      ...form
    }
  }).then(res => {
    // console.log(res);
    addModal.hide()
    document.querySelector('.add-form').reset()
    render()
  })
})

// 删除
document.querySelector('.list').addEventListener('click', function (e) {
  if (e.target.classList.contains('del')) {
    const id = e.target.dataset.id
    axios({
      url: 'http://hmajax.itheima.net/api/books/' + id,
      method: 'DELETE'
    }).then(res => {
      // console.log(res);
      render()
    })
  }
})

const modal = document.querySelector('.edit-modal')
const editModal = new bootstrap.Modal(modal)

// 点击获取详情
document.querySelector('.list').addEventListener('click', function (e) {
  // 判断是不是修改
  if (e.target.classList.contains('edit')) {
    // 获取数据的id
    const id = e.target.dataset.id
    //  console.log(id);
    // 发起修改请求
    axios({
      url: 'http://hmajax.itheima.net/api/books/' + id,
      method: 'GET'
    }).then(res => {
      Object.keys(res.data.data).forEach(item => {
        // console.log(item);
        document.querySelector(`.edit-modal .${item}`).value =
          res.data.data[item]
      })
      // 显示弹窗
      editModal.show()
    })
  }
})

// 修改
document.querySelector('.edit-btn').addEventListener('click', function (e) {
  // 收集表单数据
  const form = serialize(document.querySelector('.edit-form'), {
    hash: true,
    empty: true
  })
  axios({
    url: 'http://hmajax.itheima.net/api/books/' + form.id,
    method: 'PUT',
    data: {
      ...form,
      creator
    }
  }).then(res => {
    editModal.hide()
    render()
  })
})
